package com.szs.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.szs.exception.ClassHasStudentsException;
import com.szs.mapper.ClazzMapper;
import com.szs.pojo.Clazz;
import com.szs.pojo.ClazzQueryParam;
import com.szs.pojo.PageResult;
import com.szs.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public PageResult<Clazz> clazzPage(ClazzQueryParam clazzQueryParam) {
       //1 设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());

        //2执行查询
        List<Clazz> list = clazzMapper.list(clazzQueryParam);

        //3 解析分页结果， 封装结果
        Page<Clazz> p = (Page<Clazz>) list;
        return new PageResult<Clazz>(p.getTotal(),p.getResult());

    }
    /*
    * 新增班级信息
    * */
    @Transactional
    @Override
    public void save(Clazz clazz) {
        //1.保存班级的信息
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getClassById(Integer id) {
        return clazzMapper.getClassById(id);
    }
/*
* 修改班级信息
* */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Clazz clazz) {
        //修改班级基本信息，
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
    /*
    * 根据id删除班级信息
    * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) {
        Optional<Clazz> clazzOptional = clazzMapper.findById(id);
        if (clazzOptional.isEmpty()) {
            throw new IllegalArgumentException("班级未找到");
        }
        Clazz classObj = clazzOptional.get();
        // 检查 students 属性是否为 null
        if (classObj.getStudents() !=null && !classObj.getStudents().isEmpty()) {
            throw new ClassHasStudentsException("对不起, 该班级下有学生, 不能直接删除");
        }

        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }
}
